#include "tcp_server.h"


tcp_server::tcp_server( int port)
{
    tcp_server::port = port;
}

tcp_server::~tcp_server()
{
}

//***************************
void tcp_server::get_Website(char *url )
{
	Debug::Log("get_Website\n");
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

	std::string result;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET /inputsco.php HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
			Debug::Log("Error WSAStartup\n");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

		if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            Debug::Log("Error connect\n");
        }

		send(Socket,get_http, strlen(get_http),0 );
        char buffer[10000];
		bool bodydata=false;
        int nDataLength;
        while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
        {       
			int i = 0;
			while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
			{                    
				if (bodydata) {result+=buffer[i];}
				if (i >4) {
					if (buffer[i] == '\n' && buffer[i-1] == '\r' && buffer[i-2] == '\n' && buffer[i-3] == '\r'){bodydata=true;}
				}
                i += 1;
            }               
        }
        closesocket(Socket);
        WSACleanup();
		Debug::Log("result [ %s ]\n",result);
}

int tcp_server::start_listening()
{
	int iResult;
    WSADATA wsaData;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    int recvbuflen = DEFAULT_BUFLEN;
    char *sendbuf = "Client: sending data test";
    char recvbuf[DEFAULT_BUFLEN] = "";


    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        /*wprintf(L"WSAStartup failed with error: %d\n", iResult);*/
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        /*wprintf(L"socket failed with error: %ld\n", WSAGetLastError());*/
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    clientService.sin_port = htons( DEFAULT_PORT );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        /*wprintf(L"connect failed with error: %d\n", WSAGetLastError() );*/
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
  }
    return 0;
}

/* TODO: To change functionality
 of the server change the following function... */
int tcp_server::acceptConns()
{
    sockaddr_in from;
    int fromlen=sizeof(from);
    /* Infinte loop to echo
 the IP address of the client */
    while (true)
    {
        char temp[512];
        cSock = accept(sSock,(SOCKADDR*)&from,&fromlen);
        sprintf(temp,"Your IP address is %sn",inet_ntoa(from.sin_addr));
        send(cSock,temp,strlen(temp),0);
        std::cout << "Connection from " << inet_ntoa(from.sin_addr) <<"n";
        closesocket(cSock);
    }
    closesocket(sSock);
    WSACleanup();
    return 0;
}